﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Microsoft.SharePoint;
using CMISForSharePoint.cmisHelpers;
using CMISForSharePoint.cmisTypes;
using CMISForSharePoint.cmisEnums;
using CMISForSharePoint.Divers;
using System.Diagnostics;
using System.Reflection;

namespace  CMISForSharePoint.cmisHelpers
{

    public class CmisObjectSorter:IComparer<string>
    {
        private static string propertyName;


        public static string PropertyName 
        { 
            get
            { return propertyName; }
             set
             {propertyName=value; }
        }

        public static string GetKey(cmisObjectType obj)
        {
            cmisProperty property = null;
            if (obj == null || propertyName == string.Empty)
            {
                return string.Empty;
            }
            try
            {

                property = obj.properties.Items.Single(p => p.name == propertyName);

            }
            catch (InvalidOperationException e)
            {
                Debug.Write(e.Message);
                return string.Empty;

            }


            Type t = property.GetType();

            //we get the value of the property using reflection
            object key = t.InvokeMember("value",
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.Instance | BindingFlags.GetProperty, null,property, null);


            return key.ToString();
        }





        #region IComparer<string> Members

        public int Compare(string x, string y)
        {
            decimal a, b;
            DateTime t1,t2;
            if(decimal.TryParse(x,out a) && decimal.TryParse(y,out b))
            {
                return decimal.Compare(a,b);
            }
            else if(DateTime.TryParse(x,out t1) && DateTime.TryParse(y,out t2))
            {
                return DateTime.Compare(t1, t2);
            }
            else 
            {
                return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
            }

        }

        #endregion
    }
    
}